import React, { Component } from 'react';
import { Form, Input, InputNumber, Modal, Pagination, Space, Select } from "antd";
import TheButton from "@/components/TheButton";
import TheTable from "@/components/TheTable";
import TheImage from '@/components/TheImage';
import { apiGetUserList, } from '@/request/users';
import { sheet2Excel } from '@/utils/table2Excel.js';
import _ from 'lodash';
import "../../couponManagement/couponsList/style.scss";

/**
 * 
 * <User ref={this.UserListRef} mode={"mode"} getData={userList} userList={userList} setData={(data) => this.userListSetData(data)} />
 */

class User extends Component {
  constructor(props) {
    super(props)
    this.formRef = React.createRef()
    this.state = {
      isModalShow: false,
      selectedUserSource: [],
      selectedPageData: {
        pageNo: 1,
        pageSize: 10,
        totalCount: 0,
      },
      searchForm: {
        name: '',
      },
      userList: [],
      userListPage: {
        pageNo: 1,
        pageSize: 10,
        totalCount: 0,
      },
      dataSourceCopy: [],
      couponTableColumns: [{
        title: '用户id',
        dataIndex: 'memberId',
        key: 'memberId',
      }, {
        title: '昵称',
        dataIndex: 'nickName',
        key: 'nickName',
      }, {
        title: '手机号',
        dataIndex: 'memberMobile',
        key: 'memberMobile',
      }, {
        title: '冻结状态',
        dataIndex: 'memberStatus',
        key: 'memberStatus',
        render: text => {
          let label = ''
          switch (text) {
            case 'Y':
              label = '正常'
              break
            case 'N':
              label = '冻结'
              break
            default:
              label = '返回值错误'
              break
          }
          return label;
        }
      }, {
        title: '注销状态',
        dataIndex: 'deleted',
        key: 'deleted',
        render: text => {
          let label = ''
          switch (text) {
            case 0:
              label = '正常'
              break
            case 1:
              label = '已注销'
              break
            default:
              label = '返回值错误'
          }
          return label;
        }
      },],
      fileList: [],
      loading: false,
      disabled: false
    }
  }
  componentDidMount() {
    if(this.props.mode == "view") {
      this.setState({
        disabled: true
      })
    }
    this.getData()
  }

  getData = async (value) => {
    const { userListPage } = this.state
    let res = await apiGetUserList({ ...userListPage, ...value })
    if (res.code === 0) {
      this.setState({
        userList: res.data,
        userListPage: {
          pageNo: res.pageNo,
          pageSize: res.pageSize,
          totalCount: res.totalCount,
        },
      })
    }
  }
  // 选择弹框
  openModal() {
    this.setState({
      isModalShow: true,
      dataSourceCopy: [...this.state.selectedUserSource]
    }, () => {
      this.getSelectKeys()
      this.resetForm()
    })
  }
  // 选择商品保存
  handleOk = () => {
    this.setState({
      isModalShow: false,
      selectedUserSource: this.state.dataSourceCopy
    }, () => {
      this.props.setData(this.state.selectedUserSource)
    })
  }
  // 选择商品取消
  handleCancel = () => {
    this.setState({
      isModalShow: false
    })
  }
  // 获取当前勾选得key
  getSelectKeys() {
    const selectedRowKeys = this.state.dataSourceCopy.map(item => item.memberId)
    this.setState({
      selectedRowKeys
    })
  }
  //批量勾选
  onSelect = (record, selected, selectedRows) => {
    let dataSourceCopy = [...this.state.dataSourceCopy]
    if (selected) {
      dataSourceCopy.push({ ...record })
    } else {
      const delIndex = dataSourceCopy.findIndex(item => item.memberId === record.memberId)
      dataSourceCopy.splice(delIndex, 1)
    }
    this.setState({
      dataSourceCopy
    }, () => this.getSelectKeys())
  }
  // 勾选全部
  onSelectAll = (selected, rows, newRow) => {
    let dataSourceCopy = [...this.state.dataSourceCopy]
    if (selected) {
      dataSourceCopy = dataSourceCopy.concat(...newRow)
    } else {
      const newKeys = newRow.map(item => item.memberId)
      dataSourceCopy = dataSourceCopy.filter(item => !newKeys.includes(item.memberId))
    }
    this.setState({
      dataSourceCopy
    }, () => this.getSelectKeys())
  }
  // 选择内容分页
  selectedPageChange(e) {
    this.state.selectedPageData.pageNo = e
    this.setState({
      selectedPageData: this.state.selectedPageData
    })
  }
  // 弹框分页
  userListPageChange(e) {
    this.state.userListPage.pageNo = e
    this.setState({
      userListPage: this.state.userListPage
    }, () => {
      this.getData(this.state.searchForm)
    })
  }
  // 弹框搜索
  searchGoods() {
    const values = this.formRef.current.getFieldsValue()
    _.forIn(values, (v, k) => {
      if (v === undefined || v === '' || v === null) {
        delete (values[k])
      }
    })
    this.setState({
      searchForm: values,
      userListPage: {
        pageNo: 1,
        pageSize: this.state.userListPage.pageSize,
        totalCount: 0
      }
    }, () => this.getData(this.state.searchForm))
  }
  // 弹框重置
  resetForm() {
    this.formRef.current.resetFields()
    this.setState({
      searchForm: {
        name: '',
      }
    }, () => this.getData())
  }
  // 导入
  upload = async (e) => {
    let formData = new FormData()
    formData.append('file', e.target.files[0])
    console.log(e.target.files[0]);
    console.log(formData);
    e.target.value = ''
    fetch(React.$BaseUrl + '/trade/couponTimerCenter/uploadExcel', {
      method: "post",
      headers: {
        RSnetToken: sessionStorage.getItem('RSnetToken')
      },
      body: formData,
    })
      .then((res) => {
        this.setState({ loading: true })
        res.json().then(result => {
          if (result.code === 0) {
            this.setState({
              selectedUserSource: result.data,
              dataSourceCopy: result.data,
              loading: false
            }, () => this.props.setData(this.state.selectedUserSource))
          } else {
            React.$message({
              type: 'error',
              content: '导入错误，错误码：' + result.code
            })
            this.setState({
              loading: false
            })
          }
        })

      })
      .catch((err) => {
        React.$message({
          type: 'error',
          content: '导入失败'
        })
        this.setState({ loading: false })
      })

  }
  // 下载模板
  downloadDemo() {
    // const { dataSource } = this.state
    // const { mode } = this.props
    // const a = document.createElement('a')
    // a.href = 'https://hqmimage.oss-cn-beijing.aliyuncs.com/%E6%96%B0%E5%A2%9E%E7%A7%92%E6%9D%80%E5%95%86%E5%93%81%E6%A8%A1%E6%9D%BF.xlsx'
    // document.body.append(a)
    // a.click()
    // a.remove()
    let fileName = '用户表'
    let tH_data = [
      { prop: 'memberId', title: '用户ID' },
      { prop: 'memberMobile', title: '用户手机号' },
    ]
    let tB_data = []
    sheet2Excel({ tH_data, tB_data, fileName })
  }
  // 删除
  del = (record, index) => {
    console.log(record, index);
    const dataSource = [...this.state.selectedUserSource]
    console.log(dataSource);
    const { pageNo, pageSize } = this.state.selectedPageData
    console.log(pageNo, pageSize);
    dataSource.splice((pageNo - 1) * pageSize + index, 1)
    if(dataSource.length % pageSize === 0) {
      this.setState({
        selectedPageData: {
          pageNo: pageNo - 1,
          pageSize: 10
        }
      })
    }
    this.setState({
      selectedUserSource: dataSource
    }, () => {
      this.props.setData(this.state.selectedUserSource)
    })
  }
  render() {
    let {
      isModalShow,
      selectedUserSource,
      selectedPageData,
      couponTableColumns,
      userListPage,
      selectedRowKeys,
      userList,
      loading,
      disabled
    } = this.state;
    const rowSelection = {
      selectedRowKeys,
      onSelect: this.onSelect,
      onSelectAll: this.onSelectAll,
    };

    return (
      <div className='noCanJoinGood'>
        {
          !disabled && <Space >
            <TheButton type="default" size="middle" onClick={() => this.openModal()}>选择用户</TheButton>
            <TheButton type="default" size="middle" className="goodsImport" >
              <input type="file" className="importBtn" onChange={(e) => this.upload(e)} /> 批量导入
            </TheButton>
            {/* <Upload {...props}>
                    <TheButton size="middle" onClick={() => this.upload()} >批量导入</TheButton>
                </Upload> */}
            <TheButton type="default" size="middle" className="downloadDemo" onClick={() => this.downloadDemo()}>
              下载导入文件模板
            </TheButton>
          </Space>
        }
        <TheTable loading={loading} dataSource={selectedUserSource} bordered size="middle" style={{ width: "100%", marginTop: "10px" }}
          pagination={{
            showTotal: () => `共${selectedUserSource.length}条`,
            pageSize: selectedPageData.pageSize,
            onChange: (e) => this.selectedPageChange(e)
          }}
          columns={ disabled ? couponTableColumns :  [...couponTableColumns, {
            title: "操作",
            fixed: "right",
            width: 200,
            render: (text, render, index) => {
              return <TheButton onClick={() => this.del(render, index)}>删除</TheButton>
            },
          }]}
          rowKey={(record) => record.couponId}
        ></TheTable>
        <Modal
          width={'80%'} title={'选择用户'} visible={isModalShow} onOk={this.handleOk} onCancel={this.handleCancel}>
          <Form layout={'inline'} ref={this.formRef} style={{ lineHeight: '40px' }} >
            <Form.Item name="memberId" label='用户id' style={{ marginBottom: "10px", width: "25%" }} >
              <InputNumber placeholder="用户id" />
            </Form.Item>
            <Form.Item name="wxNickName" label='用户昵称' style={{ marginBottom: "10px", width: "25%" }}>
              <Input placeholder="用户昵称" />
            </Form.Item>
            <Form.Item name="memberStatus" label="冻结状态" style={{ marginBottom: "10px", width: "25%" }} >
              <Select options={[
                {
                  label: '正常',
                  value: 'Y'
                },
                {
                  label: '冻结',
                  value: 'N'
                }
              ]}>
              </Select>
            </Form.Item>
            <Form.Item name="deleted" label="注销状态" style={{ marginBottom: "10px", width: "25%" }} >
              <Select options={[
                {
                  label: '正常',
                  value: 0
                },
                {
                  label: '注销',
                  value: 1
                }
              ]}>
              </Select>
            </Form.Item>
            <Form.Item style={{ flex: 1, textAlign: "right" }} >
              <Space>
                <TheButton size="middle" type="primary" onClick={() => this.searchGoods()}>查询</TheButton>
                <TheButton size="middle" type="default" onClick={() => this.resetForm()}>重置</TheButton>
              </Space>
            </Form.Item>
          </Form>
          <TheTable
            style={{ margin: '10px 0' }}
            scroll={{ x: "max-content", y: '42vh' }}
            columns={couponTableColumns}
            dataSource={userList}
            rowSelection={rowSelection}
            rowKey={(record) => record.memberId}
          />
          <Pagination style={{ textAlign: 'right' }} size="small"
            current={userListPage.pageNo}
            total={userListPage.totalCount}
            showSizeChanger={false}
            onChange={this.userListPageChange.bind(this)}
          />
        </Modal>
      </div>
    );
  }
}

export default User;
